package shmallarchitect.faces.util;

import javax.faces.model.SelectItem;
import shmallarchitect.jpa.entities.User;
import shmallarchitect.jpa.jsf.UserController;

/**
 *
 * @author jaccus
 */
public class UserUtil {

    public static void copyUserProperties(User currentUser, User managedUserBean) {
        managedUserBean.setEmail(currentUser.getEmail());
        managedUserBean.setFirstName(currentUser.getFirstName());
        managedUserBean.setGalleries(currentUser.getGalleries()); //TODO: ?
        managedUserBean.setId(currentUser.getId());
        managedUserBean.setIsAdmin(currentUser.isIsAdmin());
//        managedUserBean.setIsLoggedIn(currentUser.isIsLoggedIn());
        managedUserBean.setLastName(currentUser.getLastName());
        managedUserBean.setLogin(currentUser.getLogin());
        managedUserBean.setPassword(currentUser.getPassword());
        managedUserBean.setId(currentUser.getId());
    }

    public static User findUserByCredentials(String login, String password) {

        UserController uc = new UserController();
        SelectItem[] items = uc.getUserItemsAvailableSelectMany();
        for (int i = 0; i < items.length; i++) {
            User user = (User) items[i].getValue();
            if (user.getLogin().equals(login)) {

                if(user.getPassword().equals(password))
                    return user;
                else return null;
            }
        }
        return null;
    }

    public static boolean userIdAlreadyExists(String login) {

        UserController uc = new UserController();
        SelectItem[] items = uc.getUserItemsAvailableSelectMany();
        for (int i = 0; i < items.length; i++) {
            User user = (User) items[i].getValue();
            if (user.getLogin().equals(login)) {
                return true;
            }
        }
        return false;
    }

    public static String AddRegisteredUser(User newUser) {
        if (!userIdAlreadyExists(newUser.getLogin())) {

            try {
                UserController uc = new UserController();
                User user = uc.getUser();
                copyUserProperties(newUser, user);
                uc.create();
                return user.getLogin();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;

    }
}
